﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

//This filter is tested and seems to work correctly
namespace LowLevelGraphics.Filter
{
    /// <summary>
    /// Removes interior pixels. This option sets a pixel to 0 if all its 4-connected neighbors are 1, 
    /// thus leaving only the boundary pixels on.
    /// </summary>
    /// <remarks>See http://www.johnloomis.org/ece563/notes/BinaryImages/morph/morph.html to see what result we should get</remarks>
    public class Remove : BaseForeBackgroundColorFilter
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Remove"/> class.
        /// </summary>
        public Remove()
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Remove"/> class.
        /// </summary>
        /// <param name="_remove">The _remove.</param>
        internal Remove(Remove _remove)
        {
        }

        /// <summary>
        /// Execute this Filter
        /// A Debug Statement is written if a concrete Filter is called
        /// </summary>
        /// <param name="_bitmap"></param>
        /// <returns></returns>
        public override UnsafeBitmap Execute(UnsafeBitmap _bitmap)
        {
            int y = 0;
            int x = 0;
            int nHeight = _bitmap.Height;
            int nWidth = _bitmap.Width;
         
            Color[] aColor = new Color[4];

            UnsafeBitmap bitmapCloned = (UnsafeBitmap)_bitmap.Clone();

            int nForegroundCount = 0;
            for (y = 0; y < nHeight; y++)
            {
                for (x = 0; x < nWidth; x++)
                {
                    aColor = Segmentation.GetEnvironmentPixelColorArray(bitmapCloned, x, y, Definitions.EnvironmentPointList4Clockwise, aColor);

                    nForegroundCount = 0;

                    foreach (Color colorEnvironment in aColor)
                    {
                        if (colorEnvironment == m_ColorForeground)
                        {
                            nForegroundCount++;
                        }
                    }
                    if (_bitmap.GetPixel(x, y) == m_ColorForeground)
                    {
                        _bitmap.SetPixel(x, y, nForegroundCount == 4 ? m_ColorBackground : m_ColorForeground);
                    }
                }
            }
            bitmapCloned.Dispose();
            return _bitmap;
        }

        /// <summary>
        /// This is used to clone a filter, each filter must implement it's own clone functionality
        /// </summary>
        /// <returns></returns>
        public override object Clone()
        {
            return new Remove(this);
        }
    }
}
